package com.xuzhiguang.light.gateway.core.route;

import com.xuzhiguang.light.gateway.common.utils.PropertiesUtils;
import com.xuzhiguang.light.gateway.core.filter.GatewayFilter;
import com.xuzhiguang.light.gateway.core.filter.GatewayFilterConfig;
import com.xuzhiguang.light.gateway.core.filter.factory.GatewayFilterFactory;
import com.xuzhiguang.light.gateway.core.filter.factory.GatewayFilterFactoryLoader;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author xuzhiguang
 */
@Slf4j
public class GatewayRouteBuilder {

    private String id;

    private String path;

    private URI uri;

    private List<GatewayFilter> filters;

    private int order;

    public GatewayRouteBuilder() {
        this.filters = new LinkedList<>();
    }

    public GatewayRouteBuilder config(GatewayRouteConfig config) {

        this.id = config.getId();
        this.path = config.getPath();
        try {
            this.uri = new URI(config.getUri());
        } catch (URISyntaxException ignored) {

        }

        config.getFilters().forEach((s, properties) -> {
            GatewayFilterFactory factory = GatewayFilterFactoryLoader.load(s);
            if (factory == null) {
                log.error("GatewayFilterFactory:[{}] not found", s);
            } else {
                GatewayFilterConfig gatewayFilterConfig
                        = (GatewayFilterConfig) PropertiesUtils.toBean(properties, factory.getConfigClass());
                this.filters.add(factory.apply(gatewayFilterConfig));
            }
        });

        this.order = config.getOrder();

        return this;
    }


    public GatewayRoute build() {
        return new GatewayRoute(id, path, uri, filters, order);
    }
}
